<template>
  <div class="blue-dialog track">
    <div class="dialog-wrapper">
      <div class="content">
        <div class="content-header">
          <div class="title">航飞地图</div>
          <div class="close" @click="close"></div>
        </div>

        <div class="content-body">
          <div class="btn-header">
            <div>
              设备：
              <el-select v-model="device">
                <el-option v-for="(option,i) in reactiveData.uavSnList" :key="i" :label="option.uavSn" :value="option.uavSn" @click.native="selectOneUav(option.id)"></el-option>
              </el-select>
            </div>
            <div style="display: flex;">
              <div class="fly-des">
                航飞里程: <span>{{kileValue.toFixed(2)}}km</span>
              </div>
              <div class="fly-des">
                航飞面积: <span>{{areaValue.toFixed(2)}}km²</span>
              </div>
              <el-button  type="primary" @click="optimize">轨迹优化</el-button>
            </div>
          </div>
          
          <div class="track-view">
            <div class="track-list">
              <el-scrollbar style="height:100%">
                <div class="track-list-item"  @click="selectOneTrack(option,i)" v-for="(option,i) in reactiveData.trackList" :style="{'background':  'url('+ getImage(`track/${i === trackIndex ? 'bg-active' : 'bg' }.png`) +') no-repeat','background-size':'100% 100%'}">
                  <div class="name">{{option.name}}</div>
                  <img :src="option.thumbnail" alt="">
                  <div class="status" :style="{'background-color':trackIndex === i ? '#488CFF' :'#E6E8EB'}"></div>
                </div>
              </el-scrollbar>
            </div>
            <div class="map-div">
              <div v-if="isOptimize">
                <div class="name-input" >
                  <el-input v-model="name"></el-input>
                </div>
                <div class="map-track">
                  <el-tooltip class="box-item"  effect="dark"  content="删除"  placement="left-start">
                    <img src="@/assets/image/track/ic_delete_n.png" @click="deleteOne" alt="">
                  </el-tooltip>
                  <el-tooltip class="box-item"  effect="dark"  content="撤回"  placement="left-start">
                    <img src="@/assets//image/track/ic_chehui_n.png" alt="" @click="revoke">
                  </el-tooltip>
                  <el-tooltip class="box-item"  effect="dark"  content="保存"  placement="left-start">
                    <img src="@/assets/image/track/ic_baocun_n.png" @click="save" alt="">
                  </el-tooltip>
                  <el-tooltip class="box-item"  effect="dark"  content="连接"  placement="left-start">
                    <img src="@/assets/image/track/ic_lianjie_n.png" @click="connectLine" alt="">
                  </el-tooltip>
                  <el-tooltip class="box-item"  effect="dark"  content="退出"  placement="left-start">
                    <img src="@/assets/image/track/ic_tuichu_n.png" alt="">
                  </el-tooltip>
                </div>
                <div class="track-line">
                  <el-select :disabled="id.length>0" v-model="reactiveData.showLineData" multiple  placeholder="选择轨迹" @change="changShowLine">
                    <el-option v-for="(option,index) in reactiveData.allLineData" :key="index" :label="option.name" :value="option.id"></el-option>
                  </el-select>
                </div>
              </div>
              <cesium-map></cesium-map>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang=ts>

import cesiumMap from '@/views/cesiumMap.vue';
import { getCurrentInstance, onMounted, reactive, ref ,watch} from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";

import { getflypathsbyuavid,getFlyPathAnalysisResult,uavTrailAnalysisSave,deleteAnalysisResult } from '@/api/task'

import { editActive,destroyEdit,revoke,getData } from './Entity.js'

import { getImage } from "@/utils/util";
import html2canvas from 'html2canvas'


const { appContext }:any = getCurrentInstance();
let global = appContext.config.globalProperties;

let device = ref('')
let areaValue = ref(0)
let kileValue = ref(0)
let trackIndex = ref(0)
let name = ref('')
let uavId = ref('')
let id = ref('')
let isOptimize = ref(false)

watch(trackIndex, (newValue, oldValue) => {
  name.value = reactiveData.trackList[newValue].name
})

let lineEntity: Array<any> = [];
let areaEntity: any = null


const props = defineProps<{
  trackData: Array<any>;
}>();

let reactiveData:any = reactive({
  uavSnList:[],
  trackList:[],
  showLineData:[],
  allLineData:[]
})

const optimize = () => {
  isOptimize.value = true
  editActive(global.$viewer)
}

const emit = defineEmits(["close"]);

//选择一个设备
const selectOneUav = (id:string) =>{
  uavId.value = id
}

//选择一条轨迹
const selectOneTrack = (data:any,index:number) => {
  trackIndex.value = index
  
  isOptimize.value = false
  cleanEntity()
  id.value = data.id
  if(data.flyId){
    reactiveData.showLineData = data.flyId.split(',')
  }
  if (!data.id){
    getflypathsbyuavidData()
    kileValue.value = 0
    areaValue.value = 0
  } else {
    let arr:any = []
    data.path.path.forEach((item:any) => {
      arr.push(item[0],item[1])
    })
    kileValue.value = data.mileage || 0
    areaValue.value = data.area || 0
    drawLineWithArea(arr)
  }
}

const save = async () => {
  let arr:any[]  = getData() || []
  if(arr.length<1){
    return
  }
  let mileage = Number((Custom.Measure.getDistance(arr) * 1e-3).toFixed(2)) 
  let arr1 = [...arr,arr[0]]
  let area = Number((Custom.Measure.getArea(arr1) / 1e6).toFixed(2))
  let uavSn = device.value
  let flyId = reactiveData.showLineData.join(',')

  let path:any[] = []
  arr1.forEach((item:any) =>{
    let cartographic =  Cesium.Cartographic.fromCartesian(item)
    path.push([Cesium.Math.toDegrees(cartographic.longitude),Cesium.Math.toDegrees(cartographic.latitude)])
  })
  
  let canvas = await html2canvas(document.querySelector("#cesiumContainer") as HTMLElement, {
      backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
      useCORS: true, //支持图片跨域
      scale: 0.3, //设置放大的倍数
  })

  let req = {
    id:id.value,
    flyId,
    uavId:uavId,
    name:name.value,
    uavSn,
    area,
    mileage,
    path:{path},
    base64thumbnail:canvas.toDataURL()
  }
  const res:any = await uavTrailAnalysisSave(req)
  if(res.statusCode === 200){
      ElMessage({
        type: "success",
        message: "保存成功",
      });
      getFlyPathAnalysisResultList()
      if(id){
        kileValue.value = mileage || 0
        areaValue.value = area || 0
      }
    } else {
      ElMessage({
        type: "error",
        message: "保存失败",
      });
    }
  
}

const deleteOne = async () => {
  const isCofirm = await ElMessageBox.confirm("确定删除当前的轨迹吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  });
  if (isCofirm) {
    let id = reactiveData.trackList[trackIndex.value].id
    const res:any = await deleteAnalysisResult(id)
    if(res.statusCode === 200){
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getFlyPathAnalysisResultList()
    } else {
      ElMessage({
        type: "error",
        message: "删除失败",
      });
    }
  }
}

const close = () =>{
  emit("close");
}

const connectLine = async () =>{
  const isCofirm = await ElMessageBox.confirm("确定合并当前展示的轨迹吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  });
  if (isCofirm) {
    let arr:any[] = []
    reactiveData.allLineData.forEach((item:any) => {
      if(reactiveData.showLineData.indexOf(item.id) > -1){
        arr.push(...item.path)
      }
    })
    drawLineAndFly(arr,lineEntity.length,'','#DC143C')
  } 
}

const setDefault = () => {
  props.trackData.forEach((item:any)=>{
     reactiveData.uavSnList.push({
      id:item.id,
      uavSn:item.uavSn
     });
  })
  device.value = reactiveData.uavSnList[0].uavSn
  uavId = reactiveData.uavSnList[0].id
  getflypathsbyuavidData()
}

//根据id获取详情
const getflypathsbyuavidData = async () => {
  let uavid = uavId
  reactiveData.allLineData = []
  reactiveData.showLineData = []
  const res:any =await getflypathsbyuavid({uavid})
  if(res.statusCode === 200){
    if(res.data && res.data.length){
      res.data.forEach((item:any,index:number)=>{
        let arr:any = []
        eval(item.path).forEach((task:any)=>{
          arr.push(task[0],task[1])
        })
        drawLineAndFly(arr,index,item.id)
        reactiveData.allLineData.push({
          name:`轨迹${index+1}`,
          id:item.id,
          path:arr
        })
        reactiveData.showLineData.push(item.id)
      })
      getFlyPathAnalysisResultList()
    }
  }
}

const changShowLine = (data:string[]) =>{
  lineEntity.forEach((item:any)=>{
    if(data.indexOf(item.id) > -1){
      item.show = true
    }else{
      item.show = false
    }
  })
}


//画原始轨迹线并定位  只定位索引为0的
const drawLineAndFly = (arr:any[],index:number,id:string,color:string = '#90EE90')=>{
  lineEntity[index] = global.$viewer.entities.add({
      id,
      name:'drawEntity',
      type:'polyline',
      //轨迹线
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(arr),
        show: true,
        arcType: Cesium.ArcType.RHUMB,
        material: Cesium.Color.fromCssColorString(color).withAlpha(0.8),
        width: 1.5,
        clampToGround: true
      }
  })
  if(index === 0) {
    global.$viewer.zoomTo(lineEntity[index])
  }
}

const cleanEntity = () => {
  destroyEdit(global.$viewer)
  if (lineEntity.length>0){
    lineEntity.forEach((item:any)=>{
      global.$viewer.entities.remove(item)
    })
    lineEntity = []
  }
  if (areaEntity) {
    global.$viewer.entities.remove(areaEntity)
    areaEntity =null
  }
}

// 画闭合的面 
const drawLineWithArea = (arr:any) => {
  areaEntity =  global.$viewer.entities.add({
      name:'drawEntity',
      type:'polygon',
      //轨迹线
      polygon: {
        hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
        material: Cesium.Color.fromCssColorString('#90EE90').withAlpha(0.4),
        outline: false,
        fill: true
      },
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(arr),
        show: true,
        arcType: Cesium.ArcType.RHUMB,
        material: Cesium.Color.SKYBLUE.withAlpha(0.8),
        width: 2,
        clampToGround: true
      }
  })
  global.$viewer.zoomTo(areaEntity)
}

const getFlyPathAnalysisResultList =async () => {
  let uavid = uavId
  const res:any = await getFlyPathAnalysisResult({uavid})
  if(res.statusCode === 200){
    reactiveData.trackList = res.data
    reactiveData.trackList.unshift({
      name:'原始轨迹'
    })
    name.value = reactiveData.trackList[trackIndex.value].name
  } else {

  }
}

setDefault()

</script>

<style lang='less'>
@import url('@/assets/css//dialog.less');
.track{
  .content{
    font-size: 14px;
    width: 1000px!important;
    .content-body{
      .btn-header{
        height: 40px;
        padding: 5px;
        display: flex;
        justify-content: space-between;
        .fly-des{
          margin-right: 10px;
          display: flex;
          align-items: center;
          span{
            color: #488CFF;
            margin-left: 5px;
          }
        }
      }
      .track-view{
        display: flex;
        height: 600px;
        justify-content: space-around;
        .track-list{
          width: 200px;
          height: 600px;
          .track-list-item{
            width: 180px;
            height: 170px;
            margin-bottom: 10px;
            cursor: pointer;
            .name{
              padding: 10px 15px;
            }
            img{
              padding: 5px 15px;
              height: 70px;
              width: 145px;
            }
            .status{
              height: 15px;
              width: 15px;
              border-radius: 50%;
              margin: 15px 15px;
              box-shadow: 0 0 10px #fff;
            }
          }
        }
        .map-div{
          position: relative;
          height: 100%;
          width: 750px;
          .name-input{
            position: absolute;
            z-index: 9;
            left: 20px;
            top: 20px;
            width: 200px;
            height: 40px;
          }
          .map-track{
            position: absolute;
            z-index: 9;
            right: 20px;
            top: 20px;
            height: 190px;
            width: 34px;
            background: rgba(249,252,255,0.95);
            border-radius: 4px;
            border: 1px solid #FFFFFF;
            backdrop-filter: blur(4px);
            img{
              margin: 5px;
              cursor: pointer;
            }
          }
          .track-line{
            position: absolute;
            z-index: 9;
            top: 20px;
            right: 80px;
            width: 200px;
            height: 40px;
            padding: 5px;
            border-radius: 5px;
            background-color: rgba(249,252,255,0.95);
          }
        }
      }
    }
  }
}



</style>